package com.central.apps.controller;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.cache.CfgRedisCache;
import com.central.app.common.feign.FileClient;
import com.central.app.common.feign.MessageFiles;
import com.central.app.service.*;
import com.central.apps.common.util.FileUtil;
import com.central.apps.dao.TestDao;
import com.central.apps.service.AppCustomService;
import com.central.bizcommon.annotation.log.BussinessLog;
import com.central.bizcommon.constant.MessageConstant;
import com.central.common.exception.controller.ControllerException;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.ToolUtil;
import com.central.common.web.CodeEnum;
import com.central.common.web.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;

@RestController
@Api(tags = "app的自定义api")
@RequestMapping("/appCustom")
@Slf4j
public class AppCustomController {

    @Autowired
    private AppCustomService appCustomService;
    @Autowired
    private AppCommonService appCommonService;
    @Autowired
    private AppImportService importService;
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FileClient fileClient;
    @Autowired
    private BizNumberService bizNumberService;
    @Autowired
    private CfgRedisCache cfgRedisCache;

    @Autowired
    private FlowCommonService flowCommonService;



    @GetMapping(path = "/findMaxVersion/{type}")
    public Map<String, Object> findMaxVersion(@PathVariable String type) throws Exception{
        return appCustomService.findMaxVersion(type);
    }

    @ApiOperation("工单，离线工单")
    @ApiImplicitParam(name = "ids",value = "工单id",required = true,dataType = "array")
    @PostMapping("/workorderApp/offline")
    public Result offline(@RequestBody Map<String,Object> params){
        List<Map<String, Object>> workorders = appCustomService.offline(params);
        return Result.succeed(workorders,"获取成功");
    }

    @ApiOperation("工单，上传离线工单数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "files",value = "图片",required = true,dataType = "MultipartFile"),
            @ApiImplicitParam(name = "userid",value = "用户id",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "String"),
            @ApiImplicitParam(name = "deptid",value = "部门id",required = true,dataType = "String"),
            @ApiImplicitParam(name = "deptfullname",value = "部门全名称",required = true,dataType = "String"),
            @ApiImplicitParam(name = "appid",value = "appid",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "appname",value = "appname",required = true,dataType = "String"),
            @ApiImplicitParam(name = "recordid",value = "记录id",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "encryption",value = "",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "pathid",value = "",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "params",value = "盘点单子表行数据",required = true,dataType = "json")})
    @PostMapping("/workorderApp/uploadOffline")
    @ResponseBody
    public Result uploadOffline(@RequestPart("fileList") MultipartFile[] fileList,
                                @RequestParam(value = "params",defaultValue = "{}")String params,
                                @RequestParam(value = "userid", defaultValue = "0") Integer userid,
                                @RequestParam(value = "username", defaultValue = "") String username,
                                @RequestParam(value = "deptid", defaultValue = "0") String deptid,
                                @RequestParam(value = "deptfullname", defaultValue = "") String deptfullname,
                                @RequestParam(value = "appid", defaultValue = "0") Integer appid,
                                @RequestParam(value = "appname", defaultValue = "") String appname,
                                @RequestParam(value = "recordid", defaultValue = "0") Integer recordid,
                                @RequestParam(value = "encryption", defaultValue = "1") Integer encryption,
                                @RequestParam(value = "pathid", defaultValue = "0") Integer pathid){

        String message = "上传失败";
        Integer code = CodeEnum.ERROR.getCode();
        JSONObject list = JSONObject.fromObject(params);
        try {
            handlerService.update("bl_workorder",list);
            code = CodeEnum.SUCCESS.getCode();
        } catch (Exception e) {
            log.debug(e.getMessage());
            throw  new ServiceException(e.getMessage());
        }

        // 上传图片
        MessageFiles messageFiles = fileClient.uploadfiles(fileList, userid, username, deptid, deptfullname, appid, appname, recordid, encryption, pathid);
        if (!messageFiles.isSuccess()){
            code = CodeEnum.ERROR.getCode();
            message = "上传失败";
        }
        Result result  = new Result();
        result.setCode(code);
        result.setMsg(message);
        return  result;
    }


    @ApiOperation("批量发送邮件")
    @PostMapping(path = "/webinterface/mailSend")
    @BussinessLog(module = "apps-center", value = "批量发送邮件接口")
    public Result mailSend(HttpServletRequest request,@RequestBody Map<String,Object> param) throws Exception{
        Result result = null;
//        String signMsg = appCustomService.validateRequestHeader(request);
//        if(ToolUtil.isNotEmpty(signMsg)){
//            return Result.failed(signMsg);
//        }
        try {
            result = appCustomService.mainSend(param);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            String message = MessageConstant.FAILED;
            if(e instanceof ServiceException){
                message = e.getMessage();
            }
            return Result.failed(message);
        }

        return result;
    }

    @ApiOperation("批量用户保存")
    @PostMapping(path = "/webinterface/addUsers")
    @BussinessLog(module = "apps-center", value = "批量插入用户接口")
    public Result addUsers(HttpServletRequest request,@RequestBody Map<String,Object> param) throws Exception{
        Result result = null;
//        String signMsg = appCustomService.validateRequestHeader(request);
//        if(ToolUtil.isNotEmpty(signMsg)){
//            return Result.failed(signMsg);
//        }
        try {
            result = appCustomService.userSave(param);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            String message = MessageConstant.FAILED;
            if(e instanceof ServiceException){
                message = e.getMessage();
            }
        }

        return result;
    }

    @ApiOperation("批量增加组织机构")
    @PostMapping(path = "/webinterface/addDepts")
    @BussinessLog(module = "apps-center", value = "批量增加机构接口")
    public Result addDepts(HttpServletRequest request,@RequestBody Map<String,Object> param) throws Exception{
//        String signMsg = appCustomService.validateRequestHeader(request);
//        if(ToolUtil.isNotEmpty(signMsg)){
//            return Result.failed(signMsg);
//        }
        Result result = null;
        try {
            result = appCustomService.deptSave(param);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            String message = MessageConstant.FAILED;
            if(e instanceof ServiceException){
                message = e.getMessage();
            }
        }
        return result;
    }

    @ApiOperation("批量增加供应商")
    @PostMapping(path = "/webinterface/addVendors")
    @BussinessLog(module = "apps-center", value = "批量增加供应商接口")
    public Result addVendors(HttpServletRequest request,@RequestBody Map<String,Object> param) throws Exception{
//        String signMsg = appCustomService.validateRequestHeader(request);
//        if(ToolUtil.isNotEmpty(signMsg)){
//            return Result.failed(signMsg);
//        }
        List datas = (List)param.get("data");
        try {
            datas = appCommonService.batchSaveOrUpdate("suppliermessageApp", datas);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            String message = MessageConstant.FAILED;
            if(e instanceof ServiceException){
                message = e.getMessage();
            }
        }

        return Result.succeed("操作成功");
    }


    @BussinessLog(module = "apps-center", value = "报表pdf下载")
    @GetMapping(path = "/birtpdf/download")
    public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") Long id) throws Exception{
        if(ToolUtil.isEmpty(id)){
            throw new ControllerException("请选择数据！");
        }
        List<Map<String, Object>> datas = handlerService.findBySql("select * from bl_exportreportrecord where id="+id);
        if(datas==null||datas.size()==0){
            throw new ControllerException("数据不存在！");
        }
        Map<String, Object> data = datas.get(0);
        String filepath = MapUtil.getStr(data, "filepath");
        String filename = MapUtil.getStr(data, "filename");
        if(ToolUtil.isEmpty(filepath)||ToolUtil.isEmpty(filename)){
            throw new ControllerException("文件数据存在问题！");
        }
        String filefullpath = filepath +"/"+filename;
        File file = new File(filefullpath);
        if (!file.exists()) {
            String errorMessage = "Sorry. The file you are looking for does not exist";
            throw new ControllerException(errorMessage);
        }
        String userAgent = request.getHeader("User-Agent");
        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }

        response.setContentType(mimeType);
        String downloadName;
        // 针对IE或者以IE为内核的浏览器
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            downloadName = URLEncoder.encode(filename, "UTF-8");
        } else {
            downloadName = URLEncoder.encode(filename, "utf-8").replaceAll("\\+", "%20");
        }

        byte[] encodeBytes = FileUtil.getByte(file);
        byte[] decryptEcb = encodeBytes;
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + downloadName + "");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        response.setContentLength(decryptEcb.length);
        // 指向response的输出流
        OutputStream os = response.getOutputStream();
        os.write(decryptEcb, 0, decryptEcb.length);
        os.close();
    }


    @PostMapping(path = "/webinterface/findVisit")
    @BussinessLog(module = "apps-center", value = "访问校验接口")
    public Result checkRequest(HttpServletRequest request,@RequestBody Map<String,Object> param) throws Exception{
        //从request里面获取地址
        String url = request.getRequestURL().toString();
        Result result = appCustomService.checkRequest(url,param);
        return result;
    }

    @PostMapping(path = "/changeStatus")
    @BussinessLog(module = "apps-center", value = "进行状态变更")
    public Result changeStatus(@RequestBody Map<String,Object> param) throws Exception{
        Result result = appCustomService.changeStatus(param);
        return result;
    }



}
